<?php


namespace App\Http\Middleware;


use App\Facade\AppContext;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

class OperationLog
{
    public function handle($request, \Closure $next)
    {

        /**
         * 记录后台日志
         */
        $this->buildLog($request);
        return $next($request);
    }

    public function buildLog(Request $request)
    {
        $route = Route::currentRouteAction();
        if (Str::startsWith($route, 'App\Http\Controllers') && !Str::startsWith($route, 'App\Http\Controllers\Admin')) {
            //不记录日志
        } else {
            $method = $request->getMethod();
            if ($method != 'GET') {

                \App\Models\Log\Operation::create([
                    'session_id' => $request->getSession()->getId(),
                    'ip' => $request->getClientIp(),
                    'url' => $request->url(),
                    'method' => $method,
                    'params' => json_encode($request->all()),
                    'user_id' => AppContext::userId(),
                    'hospital_id' => AppContext::hospitalId(),
                    'time' => date('Y-m-d H:i:s'),
                    'route' => $route,
                    'server_addr' => Arr::get($_SERVER, 'SERVER_ADDR', '')
                ]);
            }
        }
    }
}